package com.vehicle.controller;


import com.vehicle.service.SmsService;
import com.vehicle.util.RandomUtil;
import com.vehicle.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/send/{tel}")
    public ResultVO send(@PathVariable("tel") String tel){
        System.out.println(tel);
        //首先验证手机号
//        boolean b = RegexValidateUtil.checkMobile(tel);
//        if(!b){
//            throw new VehicleException(ResponseEnum.MOBILE_ERROR.getMsg());
//        }
        //发短信
        String code = RandomUtil.getSixBitRandom();
        System.out.println("6位数字的码为："+code);
        System.out.println(code);

        boolean send = smsService.send(tel,code);
        if(send){
            //把code存入redis
            redisTemplate.opsForValue().set("sms-code"+tel,code, 100,TimeUnit.SECONDS);
            return ResultVO.succ("短信发送成功",null);
        }
        return ResultVO.fail("短信发送失败",null);
    }

    @GetMapping("/sendOver/{userName}/{tel}")
    public ResultVO sendOver(@PathVariable("userName") String userName,@PathVariable("tel") String tel){
        System.out.println(userName);
        //发短信
        boolean send = smsService.sendOver(userName, tel);
        if(send){
            return ResultVO.succ("短信发送成功",null);
        }
        return ResultVO.fail("短信发送失败",null);
    }

}

